<template>
  <view class="login-select-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 顶部区域：LOGO和品牌名 -->
    <view class="header-section">
      <view class="brand-container">
        <image class="logo" src="/static/logo.png?v=1" mode="aspectFit"></image>
        <text class="brand-name">恒通云</text>
        <text class="brand-slogan">化工智能管理系统</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 欢迎标题 -->
      <view class="welcome-section">
        <text class="welcome-title">欢迎使用</text>
        <text class="welcome-subtitle">选择您的登录方式</text>
      </view>

      <!-- 登录选项卡片 -->
      <view class="options-container">
        <!-- 绑定手机号卡片 -->
        <view class="option-card premium-card" @click="showBindMobile">
          <view class="card-background">
            <view class="card-shine"></view>
          </view>
          <view class="card-content">
            <view class="icon-section">
              <view class="icon-wrapper premium-icon">
                <uni-icons
                  type="phone-filled"
                  size="32"
                  color="#ffffff"
                ></uni-icons>
              </view>
            </view>
            <view class="text-section">
              <text class="option-title">绑定手机号</text>
              <text class="option-desc">仅限内部员工使用，需验证手机号</text>
            </view>
            <view class="arrow-section">
              <uni-icons
                type="arrow-right"
                size="20"
                color="#ffffff"
                opacity="0.8"
              ></uni-icons>
            </view>
          </view>
        </view>
        <!-- 游客登录卡片 -->
        <view class="option-card guest-card" @click="handleGuestLogin">
          <view class="card-background">
            <view class="card-shine"></view>
          </view>
          <view class="card-content">
            <view class="icon-section">
              <view class="icon-wrapper guest-icon">
                <uni-icons
                  type="person-filled"
                  size="32"
                  color="#ffffff"
                ></uni-icons>
              </view>
            </view>
            <view class="text-section">
              <text class="option-title">游客登录</text>
              <text class="option-desc">快速登录，无需注册</text>
            </view>
            <view class="arrow-section">
              <uni-icons
                type="arrow-right"
                size="20"
                color="#ffffff"
                opacity="0.8"
              ></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 绑定手机号弹窗 -->
    <uni-popup ref="mobilePopup" type="center" :mask-click="false">
      <view class="mobile-popup-container">
        <view class="popup-card">
          <!-- 关闭按钮 -->
          <view class="close-btn" @click="closeMobilePopup">
            <uni-icons type="closeempty" size="24" color="#8f9bb3"></uni-icons>
          </view>

          <!-- 弹窗头部 -->
          <view class="popup-header">
            <view class="popup-icon">
              <uni-icons
                type="phone-filled"
                size="40"
                color="#3c9cff"
              ></uni-icons>
            </view>
            <text class="popup-title">绑定手机号</text>
            <text class="popup-subtitle"
              >仅限内部员工使用，请输入已授权的手机号</text
            >
          </view>

          <!-- 表单区域 -->
          <view class="form-section">
            <uni-forms ref="formRef" :model="mobileForm" :rules="formRules">
              <view class="input-group">
                <view class="input-label">
                  <uni-icons type="phone" size="18" color="#3c9cff"></uni-icons>
                  <text class="label-text">手机号码</text>
                </view>
                <uni-forms-item name="mobile" required>
                  <uni-easyinput
                    v-model="mobileForm.mobile"
                    type="number"
                    :maxlength="11"
                    placeholder="请输入手机号"
                    :clearable="false"
                    class="custom-input"
                  />
                </uni-forms-item>
              </view>

              <view class="input-group">
                <view class="input-label">
                  <uni-icons
                    type="locked"
                    size="18"
                    color="#3c9cff"
                  ></uni-icons>
                  <text class="label-text">验证码</text>
                </view>
                <uni-forms-item name="smsCode" required>
                  <view class="sms-input-wrapper">
                    <uni-easyinput
                      v-model="mobileForm.smsCode"
                      type="number"
                      :maxlength="6"
                      placeholder="请输入验证码"
                      :clearable="false"
                      class="custom-input sms-input"
                    />
                    <view
                      class="sms-button"
                      :class="{
                        'sms-button--disabled': smsLoading || countdown > 0,
                      }"
                      @click="sendSms"
                    >
                      <text class="sms-button-text">
                        {{
                          smsLoading
                            ? "发送中"
                            : countdown > 0
                              ? `${countdown}s`
                              : "获取验证码"
                        }}
                      </text>
                    </view>
                  </view>
                </uni-forms-item>
              </view>
            </uni-forms>
          </view>

          <!-- 操作按钮 -->
          <view class="popup-actions">
            <view
              class="primary-button"
              :class="{ 'primary-button--loading': bindLoading }"
              @click="handleBindMobile"
            >
              <text class="button-text">
                {{ bindLoading ? "绑定中..." : "确认绑定" }}
              </text>
              <view v-if="!bindLoading" class="button-shine"></view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 底部版权信息 -->
    <view class="footer-section">
      <text class="copyright-text"
        >© 2025 HengTong Tech. All Rights Reserved.</text
      >
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import useLoginApi from "./api/login";

// 从 App.vue 传递过来的微信Key
const wechatKey = ref("");
const mobilePopup = ref();
const formRef = ref();
const smsLoading = ref(false);
const bindLoading = ref(false);
const countdown = ref(0);

// 手机号绑定表单
const mobileForm = ref({
  mobile: "",
  smsCode: "",
});

// 表单验证规则
const formRules = {
  mobile: {
    rules: [
      {
        required: true,
        errorMessage: "请输入手机号",
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: "请输入正确的手机号",
      },
    ],
  },
  smsCode: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
    ],
  },
};

onMounted(() => {
  // 从路由参数或缓存中获取 wechatKey
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];

  // 先尝试从URL参数获取，再从缓存获取
  wechatKey.value =
    (currentPage as any).options?.wechatKey ||
    uni.getStorageSync("tempWechatKey") ||
    "";

  console.log("获取到的wechatKey:", wechatKey.value);
});

// 统一的登录成功处理函数
const handleLoginSuccess = async (token: string, expiresIn: number) => {
  // 1. 先存储token
  uni.setStorageSync("token", token);
  uni.setStorageSync(
    "tokenExpireTime",
    Date.now() + (expiresIn || 3600) * 1000,
  );

  // 2. 立即获取用户信息
  try {
    const userInfoRes = await useLoginApi().getUserInfo();
    // 保存用户信息到本地存储
    uni.setStorageSync("userInfo", userInfoRes);
  } catch (error) {
    console.error("获取用户信息异常:", error);
    // 即使获取用户信息失败，也不影响登录流程
  }

  // 3. 清除临时存储的微信Key
  uni.removeStorageSync("tempWechatKey");

  uni.showToast({
    title: "登录成功",
    icon: "success",
  });

  // 4. 跳转到工作台
  setTimeout(() => {
    uni.switchTab({
      url: "/pages/work/work",
    });
  }, 500);
};

// 游客登录
const handleGuestLogin = async () => {
  try {
    uni.showLoading({ title: "登录中..." });
    console.log("游客登录使用的WechatKey:", wechatKey.value);

    const res = await useLoginApi().wechatGuestLogin({
      WechatKey: wechatKey.value,
    });

    if (res.Code === 200) {
      // 使用统一的登录成功处理函数
      await handleLoginSuccess(res.Data.access_token, res.Data.expires_in);
    } else {
      uni.showToast({
        title: res.Message || "登录失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error("游客登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 显示绑定手机号弹窗
const showBindMobile = () => {
  mobilePopup.value?.open();
};

// 关闭绑定手机号弹窗
const closeMobilePopup = () => {
  mobilePopup.value?.close();
  // 重置表单
  mobileForm.value = {
    mobile: "",
    smsCode: "",
  };
  formRef.value?.clearValidate();
};

// 发送短信验证码
const sendSms = async () => {
  // 先验证手机号
  const mobileValid = await formRef.value?.validateField("mobile");
  if (!mobileValid) return;

  try {
    smsLoading.value = true;

    const res = await useLoginApi().sendLoginSms({
      Mobile: mobileForm.value.mobile,
      Type: "guestBind",
    });

    if (res.Code === 200) {
      uni.showToast({
        title: "验证码已发送",
        icon: "success",
      });

      // 开始倒计时
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      uni.showToast({
        title: res.Message || "发送失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error("发送短信失败:", error);
    uni.showToast({
      title: error.message || "发送失败",
      icon: "none",
    });
  } finally {
    smsLoading.value = false;
  }
};

// 绑定手机号
const handleBindMobile = async () => {
  // 表单验证
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    bindLoading.value = true;
    console.log("绑定手机号使用的WechatKey:", wechatKey.value);

    const res = await useLoginApi().wechatBindByMobile({
      Mobile: mobileForm.value.mobile,
      SmsCode: mobileForm.value.smsCode,
      WechatKey: wechatKey.value,
    });

    if (res.Code === 200) {
      // 使用统一的登录成功处理函数
      await handleLoginSuccess(res.Data.access_token, res.Data.expires_in);
    } else if (res.Code === 1) {
      uni.showToast({
        title: res.Message + ",请重新进入小程序重试",
        icon: "none",
      });
    } else {
      uni.showToast({
        title: res.Message,
        icon: "none",
      });
      console.log(res);
    }
  } finally {
    bindLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.login-select-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  padding-top: 70px;
  box-sizing: border-box;
}

// 背景装饰
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 6s ease-in-out infinite;

    &.circle-1 {
      width: 120rpx;
      height: 120rpx;
      top: 15%;
      right: 10%;
      animation-delay: 0s;
    }

    &.circle-2 {
      width: 80rpx;
      height: 80rpx;
      top: 35%;
      left: 8%;
      animation-delay: 2s;
    }

    &.circle-3 {
      width: 160rpx;
      height: 160rpx;
      bottom: 20%;
      right: 15%;
      animation-delay: 4s;
    }
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.header-section {
  padding: 100rpx 60rpx 80rpx;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 1;

  .brand-container {
    display: flex;
    flex-direction: column;
    align-items: center;

    .logo {
      width: 150rpx;
      height: 150rpx;
      margin-bottom: 32rpx;
    }

    .brand-name {
      font-size: 52rpx;
      font-weight: 700;
      color: #ffffff;
      text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
      margin-bottom: 12rpx;
    }

    .brand-slogan {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }
  }
}

.main-content {
  flex: 1;
  padding: 0 40rpx;
  position: relative;
  z-index: 1;

  .welcome-section {
    text-align: center;
    margin-bottom: 60rpx;

    .welcome-title {
      display: block;
      font-size: 42rpx;
      font-weight: 600;
      color: #ffffff;
      margin-bottom: 16rpx;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
    }

    .welcome-subtitle {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }

  .options-container {
    display: flex;
    flex-direction: column;
    gap: 32rpx;

    .option-card {
      position: relative;
      border-radius: 24rpx;
      overflow: hidden;
      backdrop-filter: blur(20rpx);
      transition: all 0.3s ease;
      cursor: pointer;

      &:active {
        transform: scale(0.98);
      }

      .card-background {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 0;

        .card-shine {
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            90deg,
            transparent,
            rgba(255, 255, 255, 0.2),
            transparent
          );
          animation: shine 3s infinite;
        }
      }

      .card-content {
        position: relative;
        z-index: 1;
        padding: 40rpx 32rpx;
        display: flex;
        align-items: center;

        .icon-section {
          margin-right: 24rpx;

          .icon-wrapper {
            width: 88rpx;
            height: 88rpx;
            border-radius: 22rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(10rpx);
            box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
          }
        }

        .text-section {
          flex: 1;
          position: relative;

          .option-title {
            display: block;
            font-size: 36rpx;
            font-weight: 600;
            color: #ffffff;
            margin-bottom: 8rpx;
            text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
          }

          .option-desc {
            font-size: 26rpx;
            color: rgba(255, 255, 255, 0.8);
          }
        }

        .arrow-section {
          margin-left: 24rpx;
        }
      }

      &.guest-card {
        background: linear-gradient(
          135deg,
          rgba(108, 99, 255, 0.6),
          rgba(55, 66, 250, 0.6)
        );
        border: 1rpx solid rgba(255, 255, 255, 0.2);

        .icon-wrapper {
          background: rgba(255, 255, 255, 0.2);
        }
      }

      &.premium-card {
        background: linear-gradient(
          135deg,
          rgba(60, 156, 255, 0.8),
          rgba(16, 185, 129, 0.8)
        );
        border: 1rpx solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 8rpx 32rpx rgba(60, 156, 255, 0.3);

        .icon-wrapper {
          background: rgba(255, 255, 255, 0.25);
        }
      }
    }
  }
}

@keyframes shine {
  0% {
    left: -100%;
  }
  50% {
    left: 100%;
  }
  100% {
    left: 100%;
  }
}

// 弹窗样式
.mobile-popup-container {
  width: 680rpx;
  max-width: 90vw;

  .popup-card {
    background: #ffffff;
    border-radius: 32rpx;
    overflow: hidden;
    position: relative;

    .close-btn {
      position: absolute;
      top: 24rpx;
      right: 24rpx;
      width: 48rpx;
      height: 48rpx;
      border-radius: 24rpx;
      background: #f7f8fa;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10;
    }

    .popup-header {
      text-align: center;
      padding: 60rpx 40rpx 40rpx;

      .popup-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
        background: rgba(60, 156, 255, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 24rpx;
      }

      .popup-title {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 12rpx;
      }

      .popup-subtitle {
        display: block;
        font-size: 26rpx;
        color: #8f9bb3;
        line-height: 1.4;
      }
    }

    .form-section {
      padding: 0 40rpx 20rpx;

      .input-group {
        margin-bottom: 32rpx;

        .input-label {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx;

          .label-text {
            font-size: 28rpx;
            color: #2c3e50;
            font-weight: 500;
            margin-left: 8rpx;
          }
        }

        .custom-input {
          background: #f7f8fa;
          border-radius: 12rpx;
          padding: 16rpx 20rpx;
          border: 2rpx solid transparent;
          transition: all 0.3s ease;

          &:focus {
            border-color: #3c9cff;
            background: #ffffff;
            box-shadow: 0 0 0 4rpx rgba(60, 156, 255, 0.1);
          }
        }

        .sms-input-wrapper {
          display: flex;
          align-items: center;
          gap: 16rpx;

          .sms-input {
            flex: 1;
          }

          .sms-button {
            flex-shrink: 0;
            padding: 16rpx 24rpx;
            background: linear-gradient(135deg, #3c9cff, #2979ff);
            border-radius: 12rpx;
            border: none;
            min-width: 200rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4rpx 16rpx rgba(60, 156, 255, 0.3);
            transition: all 0.3s ease;

            &:active {
              transform: scale(0.98);
            }

            .sms-button-text {
              font-size: 26rpx;
              color: #ffffff;
              font-weight: 500;
            }

            &.sms-button--disabled {
              background: #e4e7ed;
              box-shadow: none;

              .sms-button-text {
                color: #a0a4aa;
              }
            }
          }
        }
      }
    }

    .popup-actions {
      padding: 20rpx 40rpx 40rpx;

      .primary-button {
        width: 100%;
        height: 96rpx;
        background: linear-gradient(135deg, #3c9cff, #2979ff);
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;
        box-shadow: 0 8rpx 24rpx rgba(60, 156, 255, 0.4);
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.98);
        }

        .button-text {
          font-size: 32rpx;
          color: #ffffff;
          font-weight: 600;
          position: relative;
          z-index: 1;
        }

        .button-shine {
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            90deg,
            transparent,
            rgba(255, 255, 255, 0.3),
            transparent
          );
          animation: buttonShine 2s infinite;
        }

        &.primary-button--loading {
          background: #c8c9cc;
          box-shadow: none;

          .button-text {
            color: #ffffff;
          }
        }
      }
    }
  }
}

@keyframes buttonShine {
  0% {
    left: -100%;
  }
  50% {
    left: 100%;
  }
  100% {
    left: 100%;
  }
}

.footer-section {
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
  position: relative;
  z-index: 1;

  .copyright-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }
}
</style>
